CSS有許多不同的選擇器讓我們更精準也更彈性的抓取 DOM,元素,這一章示範使用偽類 :only-child 抓取只存在單一子層的元素結構。另外是以 id 為根節點,並將此發法在進行封裝,然後抓取跟節點下面元素的技巧。
//Selector API 使用實例
<div id="test">
<b>Hello</b>, I'm a ninja! <b>Hello2</b>
</div>
<div id="test2">
</div>
window.onload = function(){
var divs = document.querySelectorAll("body > div");
console.log(divs.length === 2)
var b = document.getElementById("test").querySelector("b:only-child");
console.log(b)
}
//以元素為根的查詢動作
<div id="test">
<b>Hello</b>, I'm a ninja!
<div>
window.onload = function(){
var b = document.getElementById("test").querySelector("div b");
console.log(b)
}
//強制根元素
<div id="test">
<b>Hello</b>, I'm a ninja!
<div>
(function(){
var count = 1;
this.rootedQuerySelectorAll = function(elem, query){
var oldID = elem.id;
elem.id = "rooted" + (count++);
try {
return elem.querySelectorAll("#" + elem.id + " " + query)
}
catch (e) {
throw e;
}
finally {
elem.id = oldID;
}
}
})()
window.onload = function(){
var b = rootedQuerySelectorAll(document.getElementById("test"), "div b");
console.log(b.length)
}
https://developer.mozilla.org/zh-TW/docs/Learn/Getting_started_with_the_web/CSS_basics
https://developer.mozilla.org/zh-TW/docs/Glossary/CSS_Selector
https://www.designcise.com/web/tutorial/how-to-select-the-document-root-element-with-javascript